<?php
namespace app\admin\controller;

use think\Db;
use think\Facade\Cache;
use app\admin\model\AuthRule;
use tree\Tree;
use nx\Data;

class Menu extends Admin
{
    /**
     * 菜单显示
     * @return mixed
     */
    public function index()
    {
        $data  =model('AuthRule')->order('sort asc')->select();
//        $data = menu_left($data);
        $data = $data->toArray();
        $data = Data::tree($data,'title','id','pid');
        $this->assign('authrule',$data);
        return $this->fetch();
    }

    /**
     * 新增菜单
     * @return mixed
     */
    public function add()
    {
        $this->getAuthRule();
        if (input('id')){
            $this->assign('pid',input('id'));
        }
        return $this->fetch();
    }

    /**
     * 编辑菜单
     * @return mixed
     */
    public function edit()
    {
        $this->getAuthRule();
        input('id')?$id = input('id'):$this->error('缺少参数');
        $info= Db::name('AuthRule')->where(['id'=>$id])->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    /**
     *获取所有的菜单
     */
    public function getAuthRule()
    {
        $data = model('AuthRule')->select();
        $data = menu_left($data);
        $this->assign('authrule',$data);
    }

    /**
     *添加菜单权限
     */
    public function addrun()
    {
        if(!request()->isAjax()){
            $this->error('提交方式不正确',url('admin/menu/index'));
        }else{
            $menu = new AuthRule();
            $data=input('post.');
            !empty($data['status'])?:$data['status']=0;
            $data['notcheck']==='0'?:$data['notcheck']=1;
            $pid=Db::name('auth_rule')->where(array('id'=>input('pid')))->field('level')->find();
            $level=$pid['level']+1;
            $data['level'] = $level;
            $result=$menu->validate('menu')->save($data);
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }else{
                Cache::clear('menu');
               $this->success('权限添加成功',url('admin/menu/index'));
            }
        }
    }
    /**
     *添加菜单权限
     */
    public function editrun()
    {
        if(!request()->isAjax()){
            $this->error('提交方式不正确',url('admin/menu/index'));
        }else{
            $menu = new AuthRule();
            $data=input('post.');
            !empty($data['status'])?:$data['status']=0;
            $data['notcheck']==='0'?:$data['notcheck']=1;
            $old_pid=input('old_pid');
            $old_level=input('old_level',0,'intval');
            $pid=input('pid');
            $level_diff=0;
            //判断是否更改了pid
            if($pid!=$old_pid){
                $level=Db::name('auth_rule')->where('id',$pid)->value('level')+1;
                $level_diff=($level>$old_level)?($level-$old_level):($old_level-$level);
            }else{
                $level=$old_level;
            }
            $result=$menu->allowField(true)->validate('menu')->isUpdate(true)->save($data);
            if($result!==false){
                    if($pid!=$old_pid){
                        //更新子孙级菜单的level
                        $auth_rule=Db::name('auth_rule')->order('sort')->select();
                        $tree=new Tree();
                        $tree->init($auth_rule,['parentid'=>'pid']);
                        $ids=$tree->get_childs($auth_rule,$data['id'],true,false);
                        if($ids){
                            if($level>$old_level){
                                Db::name('auth_rule')->where('id','in',$ids)->setInc('level',$level_diff);
                            }else{
                                Db::name('auth_rule')->where('id','in',$ids)->setDec('level',$level_diff);
                            }
                        }
                    }
                    Cache::clear('menu');
                    $this->success('菜单修改成功',url('admin/menu/index'));
                }else{
                    // 验证失败 输出错误信息
                    $this->error($menu->getError());
                }
        }
    }
    //删除菜单
    public function del(){
        $id = $this->request->param('id',0);
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(Db::name('AuthRule')->where('pid',$id)->find()){
            $arr=['status'=>2,'info'=>'该节点有子节点不能删除'];
        }else{
            if(AuthRule::destroy($id)){
                Cache::clear('menu');
                $arr=['status'=>1,'info'=>'删除成功'];
            } else {
                $arr=['status'=>0,'info'=>'删除失败'];
            }
        }
        return json($arr);
    }
    /**
     * 权限(后台菜单)通过复制添加
     */
    public function rule_copy()
    {
        $this->getAuthRule();
        $admin_rule=Db::name('auth_rule')->where(array('id'=>input('id')))->find();
        $this->assign('info',$admin_rule);
        return $this->fetch('copy');
    }
    /**
     * 权限(后台菜单)显示/隐藏
     */
    public function menus_rule_state()
    {
        $id=input('x');
        $statusone=Db::name('auth_rule')->where(array('id'=>$id))->value('status');//判断当前状态情况
        if($statusone==1){
            $statedata = array('status'=>0);
            Db::name('auth_rule')->where(array('id'=>$id))->setField($statedata);
            Cache::clear('menu');
            $this->success('关闭');
        }else{
            $statedata = array('status'=>1);
            Db::name('auth_rule')->where(array('id'=>$id))->setField($statedata);
            Cache::clear('menu');
            $this->success('开启');
        }
    }
}
